package com.rh.webserver.common.base.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.rh.soc.login.controller.LoginUtil;
import com.rh.soc.management.usermanage.usermanage.model.UserInfoVO;
import com.rh.webserver.common.base.bean.AppResultBean;
import com.rh.webserver.common.util.JsonUtil;
import com.rh.webserver.common.util.SessionUtil;

/**
 * Servlet Filter implementation class LicenseFilter
 */
public class FakeFilter implements Filter {

	static final Log logger = LogFactory.getLog(FakeFilter.class);

	public FakeFilter() {
	}

	public void destroy() {
	}

	public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
			throws IOException, ServletException {
		try {
			UserInfoVO vo = SessionUtil.getUser((HttpServletRequest) req);
			if (vo == null) {
				vo = new UserInfoVO();
				vo.setUserAccount("sysmanager");
				vo.setUserId("sysmanager");
				logger.info("FakeFilter login called!");
				AppResultBean bean = LoginUtil.login((HttpServletRequest) req, ((HttpServletRequest) req).getSession(),
						vo);
				if (!bean.isOkSucc()) {
					reLogin(res, bean);
					return;
				} else {
					chain.doFilter(req, res);
				}
			} else {
				chain.doFilter(req, res);
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw new IOException(e.getMessage(), e);
		}
	}

	public void reLogin(ServletResponse hres, AppResultBean bean) throws IOException {
		hres.setCharacterEncoding("utf-8");
		hres.getOutputStream().write(JsonUtil.write(bean).getBytes("utf-8"));
		hres.getOutputStream().flush();
		hres.getOutputStream().close();
	}

	public void init(FilterConfig fConfig) throws ServletException {
	}

}
